import java.util.ArrayDeque;
import java.util.Deque;

public class InorderSuccessor {

    public static TreeNode getTreeNode(TreeNode root,TreeNode p){
        Deque<TreeNode> stack=new ArrayDeque<>();
        TreeNode res=null,curr=root;
        while (!stack.isEmpty()||curr !=null){
            while (curr!=null){
                stack.push(curr);
                curr=curr.left;
            }
            curr=stack.pop();
            if(res==p){
                return curr;
            }
            res=curr;
            curr=curr.right;
        }
        return null;
    }

    public static void main(String[] args) {
        TreeNode root=new TreeNode(2);
        root.left=new TreeNode(1);
        root.right=new TreeNode(3);
        root.left.right=new TreeNode(5);
        System.out.println(getTreeNode(root,root.left).val);
    }
}
class TreeNode {
     int val;
     TreeNode left;
     TreeNode right;
     TreeNode(int x) { val = x; }
 }
